﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PropertyManagement.Core;
using PropertyManagement.Core.Model;
using PropertyManagement.Modal;

namespace PropertyManagement {
    public partial class MainForm : Form {
        SystemUserManage SystemUserManage { get; set; }
        SearchManage SearchManage { get; set; }
        HouseOwnerManage HouseOwnerManage { get; set; }
        FeeBillManage FeeBillManage { get; set; }
        MaintainManage MaintainManage { get; set; }
        DatabaseManage DatabaseManage { get; set; }
        public MainForm( ) {
            InitializeComponent( );
        }

        public MainForm(string userName, string password)
            : this( ) {
            SystemUserManage = new SystemUserManage( );
            HouseOwnerManage = new HouseOwnerManage( );
            GlobalSetting.CurrentSystemUser = SystemUserManage.Load(userName);
            SearchManage = new SearchManage( );
            FeeBillManage = new FeeBillManage( );
            MaintainManage = new MaintainManage( );
            DatabaseManage = new DatabaseManage();
        }

        private void MainForm_Load(object sender, EventArgs e) {
            GlobalSetting.MainForm = this;
            if (GlobalSetting.CurrentSystemUser == null) {
                GlobalSetting.LoginForm.Show( );
                this.Close( );
            }
            HideFeatureByRightLevel( );
            BindAllHouseOwners(dgw_houseOwners);
            this.Text = GlobalSetting.CurrentSystemUser != null
                            ? "泽云佳园小区物业管理系统-欢迎  " + GlobalSetting.CurrentSystemUser.UserName
                            : "泽云佳园小区物业管理系统";
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
            if (!GlobalSetting.IsChangeUser) {
                Application.Exit();
            }
        }

        private void HideFeatureByRightLevel( ) {
            switch (GlobalSetting.CurrentSystemUser.RightLevel) {
                case Core.RightLevel.SystremManager: {
                    tabControl1.TabPages.Remove(tabp_systemmanage);
                        break;
                    }
                case Core.RightLevel.CommonUser: {
                    tabControl1.TabPages.Remove(tabp_systemmanage);
                        //tabp_dailyManage.Hide( );
                    tabControl1.TabPages.Remove(tabp_reporting);
                        break;
                    }
                default: {
                        break;
                    }
            }
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e) {
            if (e.TabPage == tabp_systemmanage) {
                BindAllSystemUser( );
                ResetSystemUserEditPanel( );
            }
            if (e.TabPage == tabp_billmanage) {
                if (tabp_billManage_sub.SelectedTab == tabp_HouseOwnerManage) {
                    BindAllHouseOwners(dgw_houseOwners);
                }
            }
            if (e.TabPage == tabp_socialservice) {
                comboBox1.SelectedIndex = 0;
                dataGridView2.DataSource = new SortableBindingList<MaintainView>(SearchManage.SearchHistoryMaintains(false, DateTime.Today.AddDays(-10), DateTime.Today));
            }

        }

        #region system management

        private void BindAllSystemUser( ) {
            dgw_systemUser.DataSource = new SortableBindingList<SystemUser>(SearchManage.LoadAllSystemUser( ));
            dgw_systemUser.CurrentCell = null;
        }


        private void dgw_systemUser_CellClick(object sender, DataGridViewCellEventArgs e) {
            var userName = dgw_systemUser.Rows[e.RowIndex].Cells[1].Value.ToString( );
            var user = SystemUserManage.Load(userName);
            BindSystemUserInfo(user);
            ResetSystemUserEditPanel( );
        }

        private void ResetSystemUserEditPanel( ) {
            tb_username.Enabled = false;
            tb_password1.Enabled = false;
            tb_password2.Enabled = false;
            cbox_rightlevel.Enabled = false;
            //cbox_status.Enabled = false;
            button11.Enabled = false;
            button12.Enabled = false;
        }

        private void BindSystemUserInfo(SystemUser user) {
            tb_username.Text = user.UserName;
            cbox_rightlevel.SelectedIndex = (int)user.RightLevel - 1;
            //cbox_status.SelectedIndex = user.IsValid ? 0 : 1;
        }

        private void button1_Click(object sender, EventArgs e) {
            tb_username.Text = "";
            tb_username.Enabled = true;
            tb_password1.Enabled = true;
            tb_password1.Text = "";
            tb_password2.Text = "";
            tb_password2.Enabled = true;
            cbox_rightlevel.Enabled = true;
            cbox_rightlevel.SelectedIndex = 0;
            //cbox_status.Enabled = true;
            //cbox_status.SelectedIndex = 0;
            button11.Enabled = true;
            button12.Enabled = true;
            groupBox3.Tag = "creation";
            dgw_systemUser.CurrentCell = null;
        }


        private void button2_Click(object sender, EventArgs e) {

            cbox_rightlevel.Enabled = true;
            cbox_rightlevel.SelectedIndex = 0;
            //cbox_status.Enabled = true;
            //cbox_status.SelectedIndex = 0;
            button11.Enabled = true;
            button12.Enabled = true;
            groupBox3.Tag = "edit";
        }

        private void button3_Click(object sender, EventArgs e) {
            if (dgw_systemUser.CurrentCell == null) return;
            var selectingRow = dgw_systemUser.CurrentCell.RowIndex;
            var userName = dgw_systemUser.Rows[selectingRow].Cells[1].Value.ToString( );
            if (

                MessageBox.Show("是否删除该系统用户" + userName, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button2) == DialogResult.OK) {

                SystemUserManage.Remove(userName);
                FormHelper.ShowInfoMsg("删除系统用户成功");
                BindAllSystemUser( );
            }


        }

        private void button11_Click(object sender, EventArgs e) {
            if (groupBox3.Tag.ToString( ) == "creation") {
                if (string.IsNullOrEmpty(tb_username.Text.Trim( ))) {
                    FormHelper.ShowErrorMsg("请输入用户名");
                    return;
                }
                if (!string.IsNullOrEmpty(tb_password1.Text.Trim( ))) {
                    if (tb_password1.Text.ToLower( ) == tb_password2.Text.ToLower( )) {
                        var username = tb_username.Text.Trim( );
                        var password = tb_password1.Text.Trim( ).ToLower( );
                        var right = (RightLevel)(cbox_rightlevel.SelectedIndex + 1);
                       // var isValid = cbox_status.SelectedIndex == 0;
                        if (SystemUserManage.Add(username, password, right, true)) {
                            FormHelper.ShowInfoMsg("添加系统用户成功");
                        } else {
                            FormHelper.ShowErrorMsg("添加系统用户失败，该用户已存在");
                        }

                    } else {
                        FormHelper.ShowErrorMsg("两次输入的密码不一致");
                    }
                } else {
                    FormHelper.ShowErrorMsg("请输入初始密码");

                }
            } else if (groupBox3.Tag.ToString( ) == "edit") {
                var username = tb_username.Text.Trim( );
                if (string.IsNullOrEmpty(username)) {
                    FormHelper.ShowErrorMsg("请选择要编辑的用户");
                } else {
                    var user = SystemUserManage.Load(username);
                    var right = (RightLevel)(cbox_rightlevel.SelectedIndex + 1);
                    //var isValid = cbox_status.SelectedIndex == 0;
                    //user.IsValid = isValid;
                    user.RightLevel = right;
                    SystemUserManage.Update(user);
                    FormHelper.ShowInfoMsg("编辑系统用户成功");
                }
            }
            BindAllSystemUser( );
        }

        private void button12_Click(object sender, EventArgs e) {
            tb_username.Text = "";
            tb_password1.Text = "";
            tb_password2.Text = "";
            cbox_rightlevel.SelectedIndex = 0;
            //cbox_status.SelectedIndex = 0;
            ResetSystemUserEditPanel( );
        }

        private void button5_Click_1(object sender, EventArgs e) {
            if (dgw_systemUser.CurrentCell == null) return;
            var selectingRow = dgw_systemUser.CurrentCell.RowIndex;
            var userName = dgw_systemUser.Rows[selectingRow].Cells[1].Value.ToString( );
            if (

                MessageBox.Show("是否恢复该系统用户" + userName, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button2) == DialogResult.OK) {

                SystemUserManage.Revert(userName);
                FormHelper.ShowInfoMsg("恢复系统用户成功");
                BindAllSystemUser( );
            }
        }

        private void dgw_systemUser_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            if (e.RowIndex >= 0) {
                var dataItem = dgw_systemUser.Rows[e.RowIndex].DataBoundItem as SystemUser;
                if (dataItem != null && !dataItem.IsValid) {
                    dgw_systemUser.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightPink;
                }
            }
           

        }


        #endregion

        #region  menu

        private void toolStripLabel4_Click(object sender, EventArgs e) {
            if (
                MessageBox.Show("是否要退出系统", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button1) == DialogResult.Yes) {
                Application.Exit( );
            }
        }

        private void toolStripLabel1_Click(object sender, EventArgs e) {
            GlobalSetting.LoginForm.Show( );
            GlobalSetting.IsChangeUser = true;
            this.Close( );
        }

        private void toolStripLabel2_Click(object sender, EventArgs e) {
            (new EditPassword( )).ShowDialog(this);
        }

        private void toolStripLabel3_Click(object sender, EventArgs e) {
            (new PersonalInfoEditModal()).ShowDialog(this);
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e) {
            FormHelper.ShowInfoMsg("本软件由朱柯语开发，针对泽云佳园小区的物业管理业务。当前版本v1.0.0");
        }

        #endregion


        private void tabControl2_Selected(object sender, TabControlEventArgs e) {

            if (e.TabPage == tabp_HouseOwnerManage) {
                BindAllHouseOwners(dgw_houseOwners);
            }
            if (e.TabPage == tabp_feebillmanage) {
                BindAllHouseOwners(dataGridView1);
                dateTimePicker3.Value = DateTime.Today.AddDays(3);
            }
            if (e.TabPage == tabp_paidManage) {
                BindAllHouseOwners(dataGridView3);
                var allHouseOwners = SearchManage.LoadAllHouseOwner();
                textBox2.AutoCompleteCustomSource = new AutoCompleteStringCollection( );
                textBox2.AutoCompleteCustomSource.AddRange(allHouseOwners.Select(n => n.HouseCode).ToArray( ));
                textBox1.AutoCompleteCustomSource = new AutoCompleteStringCollection( );
                textBox1.AutoCompleteCustomSource.AddRange(allHouseOwners.Select(n => n.OwnerName).ToArray( ));
            }
        }

        private void BindAllHouseOwners(DataGridView listControl) {
            if (listControl == null) return;
            listControl.DataSource = new SortableBindingList<HouseOwner>(SearchManage.LoadAllHouseOwner( ));
            listControl.CurrentCell = null;
        }




        #region HouseManage

        private void button8_Click(object sender, EventArgs e) {
            (new AddHouseOwner(null, ( ) => BindAllHouseOwners(dgw_houseOwners))).ShowDialog(this);

        }

        private void button7_Click(object sender, EventArgs e) {
            var houseId = tb_search_houseid.Text.Trim( );
            dgw_houseOwners.DataSource = new SortableBindingList<HouseOwner>(SearchManage.SearchHouseOwnerByHouseCode(houseId));
        }

        private void button10_Click(object sender, EventArgs e) {
            if (dgw_houseOwners.CurrentCell != null) {
                var houseId = dgw_houseOwners.Rows[dgw_houseOwners.CurrentCell.RowIndex].Cells[0].Value.ToString( );
                var houseOwner = HouseOwnerManage.Load(houseId);
                (new AddHouseOwner(houseOwner, ( ) => BindAllHouseOwners(dgw_houseOwners))).ShowDialog(this);
            } else {
                FormHelper.ShowErrorMsg("请先选择要编辑的户主");
            }
        }

        private void button9_Click(object sender, EventArgs e) {
            if (dgw_houseOwners.CurrentCell != null) {
                var houseId = dgw_houseOwners.Rows[dgw_houseOwners.CurrentCell.RowIndex].Cells[0].Value.ToString( );
                if (
                    MessageBox.Show("是否确认要搬走[" + houseId + "]的户主", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                                    MessageBoxDefaultButton.Button1) == DialogResult.Yes) {

                    HouseOwnerManage.Remove(houseId);
                    FormHelper.ShowInfoMsg("搬迁住户成功");
                    BindAllHouseOwners(dgw_houseOwners);
                }
            } else {
                FormHelper.ShowErrorMsg("请先选择要搬走的户主");
            }
        }

        private void dgw_houseOwners_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {

        }

        #endregion


        #region BillManage
        /// <summary>
        /// search history bill
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button14_Click(object sender, EventArgs e) {
            var startDate = dateTimePicker1.Value.Date;
            var endDate = dateTimePicker3.Value.Date;
            var currentBillType = GetSelectedBillType( );
            if (currentBillType != null) {
                if (currentBillType.Value == BillType.ManagementFee || currentBillType.Value == BillType.SanitationFee) {
                    if (radioButton1.Checked) {
                        dgw_historyManagementBills.DataSource = SearchManage.SearchHistoryManagementBills(startDate,
                                                                                                          endDate,
                                                                                                          currentBillType
                                                                                                              .Value);
                    }
                    else {
                        var month = new DateTime(monthCalendar1.SelectionEnd.Year, monthCalendar1.SelectionEnd.Month, 1);
                        dgw_historyManagementBills.DataSource = SearchManage.SearchHistoryManagementBills(month,
                                                                                                          currentBillType
                                                                                                              .Value);
                    }
                   
                } else {
                    if (radioButton1.Checked) {
                        dgw_historyInstrumentBills.DataSource = SearchManage.SearchHistoryInstrumentBills(startDate, endDate,
                                                                                                    currentBillType
                                                                                                        .Value);
                    }
                    else {
                        var month = new DateTime(monthCalendar1.SelectionEnd.Year, monthCalendar1.SelectionEnd.Month, 1);
                        dgw_historyInstrumentBills.DataSource = SearchManage.SearchHistoryInstrumentBills(month,
                                                                                                          currentBillType
                                                                                                              .Value);
                    }
                   
                }
            } else {
                FormHelper.ShowErrorMsg("请先选择收费种类");
            }


        }

        private SortableBindingList<EmptyFeeInstrumentBill> currentFeeInstrumentBills;
        private SortableBindingList<EmptyFeeManagementBill> currentFeeManagementBills;

        private BillType? GetSelectedBillType( ) {
            if (treeView1.SelectedNode != null) {
                switch (treeView1.SelectedNode.Name) {
                    case "manageFee":
                        return BillType.ManagementFee;
                    case "sanitationFee":
                        return BillType.SanitationFee;
                    case "waterFee":
                        return BillType.WaterFee;
                    case "gasFee":
                        return BillType.GasFee;
                    case "elecFee":
                        return BillType.ElectricFee;
                    default:
                        return null;
                }

            }
            return null;
        }

        private void button13_Click(object sender, EventArgs e) {
            var currentBillType = GetSelectedBillType( );
            if (currentBillType != null) {
                var userList = GetTargetUsers( );
                if (userList == null || !userList.Any( )) {
                    FormHelper.ShowErrorMsg("请先选择要收费的住户");
                    return;
                }
                if (currentBillType.Value == BillType.ManagementFee || currentBillType.Value == BillType.SanitationFee) {

                    BindEmptyManagementBills(
                        userList.Select(u => FeeBillManage.CreationEmptyManagementBill(currentBillType.Value, u)).Where(n=>n!=null));
                } else {
                    BindEmptyInstrumentBills(
                        userList.Select(u => FeeBillManage.CreationEmptyFeeInstrumentBill(currentBillType.Value, u)).Where(n => n != null));
                }

            } else {
                FormHelper.ShowErrorMsg("请先选择收费种类");
            }

        }

        private void BindEmptyInstrumentBills(IEnumerable<EmptyFeeInstrumentBill> iEnumerable) {
            currentFeeInstrumentBills = new SortableBindingList<EmptyFeeInstrumentBill>(iEnumerable); ;
            dgw_billViewlist2.DataSource = currentFeeInstrumentBills;
        }

        private void BindEmptyManagementBills(IEnumerable<EmptyFeeManagementBill> iEnumerable) {
            currentFeeManagementBills = new SortableBindingList<EmptyFeeManagementBill>(iEnumerable); ;
            dgw_billViewList1.DataSource = currentFeeManagementBills;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e) {
            foreach (DataGridViewRow r in dataGridView1.Rows) {
                var cell = r.Cells[0] as DataGridViewCheckBoxCell;
                if (cell != null) {
                    cell.Value = checkBox1.Checked;
                }
            }
        }

        private IEnumerable<HouseOwner> GetTargetUsers( ) {
            List<HouseOwner> owners = new List<HouseOwner>( );
            foreach (DataGridViewRow r in dataGridView1.Rows) {
                var cell = r.Cells[0] as DataGridViewCheckBoxCell;
                if (cell != null && cell.Value != null && (bool)cell.Value) {
                    owners.Add(r.DataBoundItem as HouseOwner);
                }
            }
            return owners.Where(n => n != null);
        }

        private void SetGridView(BillType? type) {
            dgw_billViewList1.AutoGenerateColumns = false;
            dgw_billViewlist2.AutoGenerateColumns = false;
            dgw_historyInstrumentBills.AutoGenerateColumns = false;
            dgw_historyManagementBills.AutoGenerateColumns = false;
            dgw_billViewList1.DataSource = null;
            dgw_billViewlist2.DataSource = null;
            dgw_historyInstrumentBills.DataSource = null;
            dgw_historyManagementBills.DataSource = null;
            dgw_billViewList1.Visible = false;
            dgw_billViewlist2.Visible = false;
           dgw_historyInstrumentBills.Visible = false;
            dgw_historyManagementBills.Visible = false;

            switch (type) {
                case BillType.ManagementFee:
                case BillType.SanitationFee: {
                        dgw_billViewList1.Visible = true;
                        dgw_historyManagementBills.Visible = true;
                        break;
                    }
                case BillType.ElectricFee:
                case BillType.GasFee:
                case BillType.WaterFee: {
                        dgw_billViewlist2.Visible = true;
                        dgw_historyInstrumentBills.Visible = true;
                        break;
                    }
                default: {
                        break;

                    }



            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
            var type = GetSelectedBillType( );
            SetGridView(type);
        }

        private void dgw_billViewlist2_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            if (e.RowIndex >= 0) {
                var bill = dgw_billViewlist2.Rows[e.RowIndex].DataBoundItem as EmptyFeeInstrumentBill;
                if (bill != null) {
                    (new InstrumentBillEditorForm(bill, ( ) => dgw_billViewlist2.Refresh( ))).ShowDialog(this);
                }
            }
            
        }

        private void button15_Click(object sender, EventArgs e) {
            button15.Enabled = false;
            var currentBillType = GetSelectedBillType( );
            if (currentBillType != null) {
                try {
                    if (currentBillType.Value == BillType.ManagementFee ||
                        currentBillType.Value == BillType.SanitationFee) {
                        FeeBillManage.SaveManagementBills(currentFeeManagementBills);
                    }
                    else {
                        FeeBillManage.SaveInstrumentBills(currentFeeInstrumentBills);
                    }
                    FormHelper.ShowInfoMsg("账单已保存");
                    var type = GetSelectedBillType( );
                    SetGridView(type);
                }
                catch {
                    FormHelper.ShowErrorMsg("保存账单失败");
                }
                finally {
                    button15.Enabled = true;
                }
            } else {
                FormHelper.ShowErrorMsg("请先选择收费种类");
            }
        }

        private void button16_Click(object sender, EventArgs e) {
            currentFeeManagementBills = null;
            currentFeeInstrumentBills = null;
            dgw_billViewList1.DataSource = null;
            dgw_billViewlist2.DataSource = null;
        }

       

        private void dgw_historyInstrumentBills_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            var dataItem = dgw_historyInstrumentBills.Rows[e.RowIndex].DataBoundItem as HistoryInstrumentBill;
            if (dataItem.IsCompletedPaid) {
                dgw_historyInstrumentBills.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightBlue;
            } else {
                dgw_historyInstrumentBills.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightPink;
            }
            //if (dataItem.PaidDate.Date == DateTime.MinValue.Date || dataItem.PaidDate.Date == DateTime.MaxValue.Date) {
            //    dgw_historyInstrumentBills.Rows[e.RowIndex].Cells[9].Value = "--";
            //}
        }

        //private void dgw_billViewlist2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
        //    var dataItem = dgw_billViewlist2.Rows[e.RowIndex].DataBoundItem as EmptyFeeInstrumentBill;
        //    if (dataItem.LastDate == DateTime.MinValue || dataItem.LastDate == DateTime.MaxValue) {
        //        dgw_billViewlist2.Rows[e.RowIndex].Cells["Bill2_LastDate"].Value = "";
        //    }
        //    if (dataItem.CurrentDate == null || dataItem.CurrentDate.Value.Date == DateTime.MinValue.Date || dataItem.CurrentDate.Value.Date == DateTime.MaxValue.Date) {
        //        dgw_billViewlist2.Rows[e.RowIndex].Cells["Bill2_CurrentDate"].Value = "";
        //    }
        //}

        private void dgw_billViewList1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            
        }

      

        private void dgw_historyManagementBills_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            var dataItem = dgw_historyManagementBills.Rows[e.RowIndex].DataBoundItem as HistoryManagementBill;
            if (dataItem.IsCompletedPaid) {
                dgw_historyManagementBills.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightBlue;
            } else {
                dgw_historyManagementBills.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightPink;
            }
            //if (dataItem.PaidDate.Date == DateTime.MinValue.Date || dataItem.PaidDate.Date == DateTime.MaxValue.Date) {
            //    dgw_historyManagementBills.Rows[e.RowIndex].Cells[9].Value = "--";
            //}
        }

        private void button6_Click_1(object sender, EventArgs e) {
            var currentBillType = GetSelectedBillType( );
            if (currentBillType != null) {
                (new UnitPriceEditor(currentBillType.Value)).ShowDialog(this);
            } else {
                FormHelper.ShowErrorMsg("请先选择收费种类");
            }
           
        }

        private void textBox4_Click(object sender, EventArgs e) {
           
                monthCalendar1.Visible = !monthCalendar1.Visible;
            
        }

        private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e) {
            textBox4.Text = (new DateTime(e.End.Year, e.End.Month, 1)).ToString("yyyy-MM");
            monthCalendar1.Visible = false;
        }

        

        #endregion

        #region  Maintain

        private void button20_Click(object sender, EventArgs e) {
            SearchMaintain();
        }

        private void SearchMaintain() {
            var stime = dateTimePicker2.Value.Date;
            var etime = dateTimePicker4.Value.Date;
            bool? isRepaired = null;
            if (comboBox1.SelectedItem.ToString() == "未修") {
                isRepaired = false;
            }
            else if (comboBox1.SelectedItem.ToString() == "已修") {
                isRepaired = true;
            }
            dataGridView2.DataSource = new SortableBindingList<MaintainView>(SearchManage.SearchHistoryMaintains(isRepaired, stime, etime));
        }

        private void button17_Click(object sender, EventArgs e) {
            var form = (new MaintainForm( ));
            form.OnCreated += (s, args) => {
                var time = DateTime.Now.Date;
                dataGridView2.DataSource = new SortableBindingList<MaintainView>(SearchManage.SearchHistoryMaintains(null, time, time).OrderByDescending(n => n.LastUpdate).Take(1));
            };
           form.ShowDialog(this);
             
        }


        private void button18_Click(object sender, EventArgs e) {
            if (dataGridView2.SelectedRows != null && dataGridView2.SelectedRows.Count == 1) {
                var maintainView = dataGridView2.SelectedRows[0].DataBoundItem as MaintainView;
                if (maintainView != null) {
                    var form = (new MaintainForm(maintainView));
                    form.OnUpdated += (s, args) => SearchMaintain();
                   form.ShowDialog(this);
                }
            }

        }

        private void button19_Click(object sender, EventArgs e) {
            if (dataGridView2.SelectedRows != null && dataGridView2.SelectedRows.Count == 1) {
                var maintainView = dataGridView2.SelectedRows[0].DataBoundItem as MaintainView;

                if (maintainView != null) {
                    if (MessageBox.Show("确定删除维修单号" + maintainView.MaintainCode + "吗？", "提示", MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) {
                        var maintain = MaintainManage.GetById(maintainView.MaintainID);
                        MaintainManage.Remove(maintain);
                        SearchMaintain( );
                    }
                }
            }
        }

       

        private void dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            var dataItem = dataGridView2.Rows[e.RowIndex].DataBoundItem as MaintainView;
            dataGridView2.Rows[e.RowIndex].Cells[9].Value = dataItem.MaintainFee.ToString("C");
            if (dataItem.RepaireDate.Date == DateTime.MinValue.Date || dataItem.RepaireDate.Date == DateTime.MaxValue.Date) {
                dataGridView2.Rows[e.RowIndex].Cells[10].Value = "";
            }
        }
        #endregion

        #region  PaidManage
        private void button21_Click(object sender, EventArgs e) {
            var code = textBox2.Text.Trim();
            var name = textBox1.Text.Trim();
            var owners = SearchManage.SearchHouseOwnerByHouseCodeOrOnwerName(code, name);
            dataGridView3.DataSource = new SortableBindingList<HouseOwner>(owners);
        }

        private HouseOwner currentSelectedHouseOwnerInfo;
        private DateTime? currentSelectMonth;
        private void dataGridView3_CellClick(object sender, DataGridViewCellEventArgs e) {
            if (e.RowIndex >= 0) {
                var item = dataGridView3.Rows[e.RowIndex].DataBoundItem as HouseOwner;
                currentSelectedHouseOwnerInfo = item;
                BindUnPaidBills(item, currentSelectMonth);
                
            }
        }

        private void BindUnPaidBills(HouseOwner item,DateTime? month) {
            currentHouseUnpaidBills = SearchManage.SearchUnPaidHistoryBillsByHouse(item.HouseOwnerID, month);
            dataGridView5.DataSource = new SortableBindingList<HistoryBill>(currentHouseUnpaidBills);
            label18.Text = item.HouseCode;
            label20.Text = item.OwnerName;
            label22.Text = currentHouseUnpaidBills.Count().ToString();
            label26.Text = currentHouseUnpaidBills.Sum(b => b.CallableMoney).ToString("￥#00.00");

            label24.Text = label22.Text;
            label28.Text = label26.Text;
            label30.Text = currentHouseUnpaidBills.Sum(b => GetOverDateFee(b)).ToString("￥#00.00");
        }

        private IEnumerable<HistoryBill> currentHouseUnpaidBills;

       

        private void dataGridView5_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            //var dataItem = dataGridView5.Rows[e.RowIndex].DataBoundItem as HistoryBill;
            //if (dataItem.PaidDate == DateTime.MinValue || dataItem.PaidDate == DateTime.MaxValue) {
            //    dataGridView5.Rows[e.RowIndex].Cells["PaidDate"].Value = "";
            //}
        }

        private decimal GetOverDateFee(HistoryBill bill) {
            if (DateTime.Today <= bill.ExpireDate) {
                return 0m;
            }
            else {
                var overDay = (DateTime.Today - bill.ExpireDate).Days;
                bill.OverdueFee = (decimal)((double)bill.CallableMoney * Math.Pow((1 + 0.02), overDay));
                return bill.OverdueFee;

            }
           
        }

        private void button22_Click(object sender, EventArgs e) {
            if (MessageBox.Show("确认已缴纳这些账单费用？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button1)
                == DialogResult.Yes
                ) {
               var bills =  currentHouseUnpaidBills.Select(n => {
                    var bill = FeeBillManage.GetBillById(n.BillID);
                    bill.PaidDate = DateTime.Today;
                    bill.PaidMoney = n.CallableMoney + n.OverdueFee;
                    bill.OverdueFee = n.OverdueFee;
                    return bill;
                });

                FeeBillManage.PaidBills(bills);
                var item = dataGridView3.SelectedRows[0].DataBoundItem as HouseOwner;
                currentHouseUnpaidBills = SearchManage.SearchUnPaidHistoryBillsByHouse(item.HouseOwnerID);
                dataGridView5.DataSource = new SortableBindingList<HistoryBill>(currentHouseUnpaidBills);
            }
        }

        private void textBox5_Click(object sender, EventArgs e) {
            if (checkBox2.Checked) {
                monthCalendar2.Visible = !monthCalendar2.Visible;
            }
            
        }

        private void monthCalendar2_DateSelected(object sender, DateRangeEventArgs e) {
            textBox5.Text = (new DateTime(e.End.Year, e.End.Month, 1)).ToString("yyyy-MM");
            currentSelectMonth = (new DateTime(e.End.Year, e.End.Month, 1));
            if (currentSelectedHouseOwnerInfo == null) {
                FormHelper.ShowErrorMsg("请先选择业主");
            }
            else {
                BindUnPaidBills(currentSelectedHouseOwnerInfo, currentSelectMonth);
            }
            monthCalendar2.Visible = false;
        }

        #endregion

        #region Reportion
        private void button23_Click(object sender, EventArgs e) {
            if (radioButton3.Checked) {
                var startDate = dateTimePicker5.Value.Date;
                var endDate = dateTimePicker6.Value.Date.AddHours(23).AddMinutes(59);
                var list = SearchManage.GetFeeBillsReporting(startDate, endDate);
                dataGridView4.DataSource = list;
                label35.Text = list.Count( ).ToString( );
                label37.Text = list.Sum(r => r.TotalFee).ToString( );
            }else if (radioButton4.Checked) {
                var month = new DateTime(monthCalendar3.SelectionEnd.Year, monthCalendar3.SelectionEnd.Month, 1);
                var list = SearchManage.GetFeeBillsReporting(month);
                dataGridView4.DataSource = list;
                label35.Text = list.Count( ).ToString( );
                label37.Text = list.Sum(r => r.TotalFee).ToString( );
            }
            

        }

        private void textBox6_Click(object sender, EventArgs e) {
            monthCalendar3.Visible = !monthCalendar3.Visible;
        }

        private void monthCalendar3_DateSelected(object sender, DateRangeEventArgs e) {
            textBox6.Text = (new DateTime(e.End.Year, e.End.Month, 1)).ToString("yyyy-MM");
            monthCalendar3.Visible = false;
        }

        private void dataGridView4_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
            
            
        }

        private void dataGridView4_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) {
            var dataItem = dataGridView4.Rows[e.RowIndex].DataBoundItem as PropertyManagementFeeReport;
        }
        #endregion

        private void button4_Click(object sender, EventArgs e) {
            if (MessageBox.Show("是否要初始化数据库？该操作将清除所有已有数据！", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button2) == DialogResult.OK) {
                try {
                    DatabaseManage.InitDatabase();
                }
                catch {
                    FormHelper.ShowErrorMsg("初始化数据库失败，请重试");
                }
                
            }
           
        }

        private void button5_Click(object sender, EventArgs e) {
            saveFileDialog1.DefaultExt = ".bak";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
                string file = saveFileDialog1.FileName;
                if (DatabaseManage.Backup(file)) {
                    FormHelper.ShowInfoMsg("完全备份成功，文件" + file);
                } else {
                    FormHelper.ShowErrorMsg("备份失败");
                }
            }
            
        }

        private void button6_Click(object sender, EventArgs e) {
            string file = OpenFile();
            if (file!=string.Empty&&File.Exists(file)) {
                if (DatabaseManage.Restore(file)) {
                    FormHelper.ShowInfoMsg("恢复成功");
                } else {
                    FormHelper.ShowErrorMsg("恢复失败");
                }
                
            }
            else {
                FormHelper.ShowErrorMsg("备份文件不存在");
            }
        }

        private string OpenFile() {
            if (openFileDialog1.ShowDialog() == DialogResult.OK) {
                string extName = Path.GetExtension(openFileDialog1.FileName);
                if (extName != ".bak") {
                    FormHelper.ShowErrorMsg("要恢复的备份文件必须是.bak");
                    return "";
                }
                return openFileDialog1.FileName;
            }
            return "";
        }

       

       

        

        

        

        

        

        
        

        

       

       

        

        

        

        

        

       

       

       

      

        

     

      
        

       
       

    

       

        
        



































































    }
}
